package com.xyzisme76.application;


import com.xyzisme76.dao.UserDao;
import com.xyzisme76.pojo.Course;
import com.xyzisme76.pojo.Sc;
import com.xyzisme76.pojo.User;
import com.xyzisme76.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

public class RootIndex {
    private static final int WIDTH =700;
    private static final int HEIGHT =500;

    public void rootIndexInfo(){
        JFrame jf = new JFrame("RootIndex");
        jf.setSize(new Dimension(WIDTH,HEIGHT));
        //jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        //测试时方便快速退出

        // 所在位置 居中
        jf.setLocationRelativeTo(null);

        jf.setResizable(false);
        // 设置居中

        JButton addButton = new JButton("添加");
        JButton delButton = new JButton("删除");
        JButton chgButton = new JButton("修改");
        JTextField uid = new JTextField(10);
        JTextField userName = new JTextField(10);
        JTextField psd = new JTextField(10);
        JTextField id = new JTextField(10);
        //忘记加提示了，又不想改格式，就这样写算了；
//        JTextArea name = new JTextArea("用户Id：                    用户名：                    密码：                     权限Id:      ");

        List<User> userList = GetInformation.getSt();
        Iterator var = userList.iterator();
        int forNut = userList.size();
        Object[] columnNames = {"用户ID","用户名", "密码", "权限ID"};
        Object[][] rowData = new Object[forNut][4];// 表格所有行数据
        int i = 0;
        while(var.hasNext()) {
            User user = (User) var.next();
            rowData[i][0] = user.getUid();
            rowData[i][1] = user.getName();
            rowData[i][2] = user.getPwd();
            rowData[i][3] = user.getId();
            i++;
        }

        TableModel tableModel = new DefaultTableModel(rowData, columnNames);
        JTable table = new JTable(tableModel);


        // 使用 表格模型 创建 行排序器（TableRowSorter 实现了 RowSorter）
        //RowSorter<TableModel> rowSorter = new TableRowSorter<TableModel>(tableModel);
        // 给 表格 设置 行排序器
        //table.setRowSorter(rowSorter);




        JPanel jp = new JPanel() {
            protected void paintComponent(Graphics g) {
                try {
                    Image bg = ImageIO.read(new File(
                            "src/main/java/com/xyzisme76/application/images/background4.png"));
                    g.drawImage(bg, 0, 0, getWidth(), getHeight(), null);
                }catch(IOException e) {
                    e.printStackTrace();
                }
            }
        };

        jp.setLayout(null);
        //布局太麻烦了，直接绝对位置
        jf.setContentPane(jp);

        jp.add(uid);
        jp.add(userName);
        jp.add(psd);
        jp.add(id);
//        jp.add(name);
        jp.add(addButton);
        jp.add(delButton);
        jp.add(chgButton);
        // 把 表头 添加到容器顶部（使用普通的中间容器添加表格时，表头 和 内容 需要分开添加）
        jp.add(table.getTableHeader());
        // 把 表格内容 添加到容器中心
        jp.add(table);

//        name.setForeground(Color.DARK_GRAY);
//        name.setFont(new Font("微软雅黑", Font.BOLD, 15));


        addButton.setForeground(Color.DARK_GRAY);
        addButton.setBackground(Color.white);
        addButton.setFont(new Font("微软雅黑", Font.BOLD, 15));
        delButton.setForeground(Color.DARK_GRAY);
        delButton.setBackground(Color.white);
        delButton.setFont(new Font("微软雅黑", Font.BOLD, 15));
        chgButton.setForeground(Color.DARK_GRAY);
        chgButton.setBackground(Color.white);
        chgButton.setFont(new Font("微软雅黑", Font.BOLD, 15));

        final int x = 135,y = 90;
        addButton.setBounds(140,140,y,30);
        delButton.setBounds(160 + x, 140, y,30);
        chgButton.setBounds(180 + 2 * x, 140,y,30);

//        name.setBounds(65,60, 600,30);
        uid.setBounds(55,90, x,30);
        //userName.setBounds(65, 40, x, 30);
        userName.setBounds(70 + x,90,x,30);
        psd.setBounds(95 + 2 * x,90,x,30);
        id.setBounds(120 + 3 * x,90,x,30);
        table.setBounds(65, 230, 400, 400);
        table.getTableHeader().setBounds(65,190,400,30);
        jf.setVisible(true);

        addButton.addActionListener(e->{
            String names, pwds;
            names = userName.getText();
            int ids =  Integer.parseInt(id.getText());
            pwds = psd.getText();
            User user = new User(ids,names,pwds);
            System.out.println(user);
            AddUser.addItem(user);

//            List<User> userList2 = GetInformation.getSt();
//            Iterator var2 = userList2.iterator();
//            int forNut2 = userList2.size();
//            Object[] columnNames2 = {"用户名", "密码", "权限ID"};
//            Object[][] rowData2 = new Object[forNut2][3];// 表格所有行数据
//            int t = 0;
//            while(var2.hasNext()) {
//                User user2 = (User) var2.next();
//                rowData2[t][0] = user2.getName();
//                rowData2[t][1] = user2.getPwd();
//                rowData2[t][2] = user2.getId();
//                t++;
//            }
//            TableModel tableModels2 = new DefaultTableModel(rowData2, columnNames2);
//            table.setModel(tableModels2);
            JOptionPane.showMessageDialog(null,"添加成功，刷新后可见！");
            jf.dispose();
            new RootIndex();
        });

        delButton.addActionListener(e->{

            int userId = Integer.parseInt(uid.getText());

            DelUser.delItem(userId);
            JOptionPane.showMessageDialog(null,"删除成功");
            jf.dispose();
            new RootIndex();
        });

        chgButton.addActionListener(e->{
            String names, pwds;
            int userId=Integer.parseInt(uid.getText());
            names = userName.getText();
            int ids =  Integer.parseInt(id.getText());
            pwds = psd.getText();
            User user = new User(userId,names,pwds,ids);
            ChgUser.chgItem(user);
            JOptionPane.showMessageDialog(null,"修改成功");
            jf.dispose();
            new RootIndex();
        });
    }
    RootIndex(){
        rootIndexInfo();
    }

}

class GetInformation {
    static List<User> getSt() {
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        List<User> userList = userDao.getUserList();
        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
        return userList;
    }

}

class AddUser{
    static void addItem(User user){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        userDao.addUser(user);
        sqlSession.commit();
        sqlSession.close();
    }
}

class DelUser{
    static void delItem(int uid){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        userDao.delUser(uid);
        sqlSession.commit();
        sqlSession.close();
    }
}
class ChgUser{
    static void chgItem(User user){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        userDao.chgUser(user);
        sqlSession.commit();
        sqlSession.close();
    }
}